package com.lyj.thread.readwritelock;

import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 *ReadWriteLock 读写锁
 */
public class ReadWritelockDemo {

    public static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public static ReentrantReadWriteLock.ReadLock  readLock = readWriteLock.readLock();

    public static ReentrantReadWriteLock.WriteLock  writeLock = readWriteLock.writeLock();

//    public static void main(String[] args) {
//
//        for (int i = 0; i < 10 ; i++) {
//            new Thread(() ->{
//                read(readLock , " 正在读数据");
//            }).start();
//        }
//        for (int i = 0; i < 10 ; i++) {
//            new Thread(() ->{
//                write(writeLock , " 正在写数据");
//            }).start();
//        }
//    }
//
//    public static void read(Lock lock , String s) {
//        try {
//            lock.lock();
//            System.out.println(Thread.currentThread().getName() + s );
//            TimeUnit.MILLISECONDS.sleep(1000);
//        }catch (Exception e) {
//            e.printStackTrace();
//        }finally {
//            lock.unlock();
//        }
//    }


    public static void main(String[] args) {
        Thread thread0 = new Thread(() -> {
            readLock.lock();
            try {
                System.out.println("Thread 1 running " + new Date());
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                readLock.unlock();
            }
        },"t1");

        Thread thread1 = new Thread(() -> {
            writeLock.lock();
            try {
                System.out.println("Thread 2 running " + new Date());
//                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                writeLock.unlock();
            }
        },"t2");

        thread0.start();
        thread1.start();


    }
    public static void write(Lock lock , String s) {
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + s );
            TimeUnit.MILLISECONDS.sleep(1000);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
